import $ from 'jquery';
import 'froala-editor';
import 'froala-editor/js/languages/zh_cn';
import 'froala-editor/js/plugins/align.min';
import 'froala-editor/js/plugins/colors.min';
import 'froala-editor/js/plugins/font_family.min';
import 'froala-editor/js/plugins/font_size.min';
import 'froala-editor/css/plugins/colors.min.css'

import { SEALS } from '../../../config/static';

import domtoimage from 'dom-to-image';

import util from '@/libs/util';
import Cookies from 'js-cookie';
import CONSTANTS from '@/config/constants';
import getDate from '@/util/getDate.js';
import DragDropContainer from '../dragDropContainer/dragDropContainer.vue'

const DEFAULT_SEAL_WIDTH = 200

export default {
    components: { DragDropContainer },
    data() {
        return {
            imageDataUrl: '',
            editorInst: null,
            makeTemplate: {
                backgroundUrl: '',
                sprites: []
            },
            seals: SEALS,

            backgroundImages: [],

            variables: [{
                name: 'name',
                placeholder: '姓名',
                text: '姓名'
            }, {
                name: 'theme',
                placeholder: '主题',
                text: '主题'
            }, {
                name: 'diplomas',
                placeholder: '奖项',
                text: '奖项'
            }, {
                name: 'school',
                placeholder: '学校',
                text: '学校'
            }, {
                name: 'spare1',
                placeholder: '备用1',
                text: '备用1'
            }, {
                name: 'spare2',
                placeholder: '备用2',
                text: '备用2'
            }, {
                name: 'spare3',
                placeholder: '备用3',
                text: '备用3'
            }],

            activeSpriteIndex: -1,

            bgPickerVisible: false,
            bgUrlTemp: '',
            $previewContainer: null,
            $bgEl: null,
            baseuser: JSON.parse(Cookies.get('baseUser')),
            modelName: '',
            diplomasId: '',
            formData: {},
            QRcode: CONSTANTS.LOCAL_HOST + '/static/img/QRcode.png',

            isFullscreen: false,
            defaultFontSize: 15,
            isPreview: false,
            themeList: [],
            theme: [],
            themeId: '',
            diplomasList: [],
            allMember: [],
            numList: [1, 2, 3, 4, 5],
            preForm: {},
            preTemplate: {}
        }
    },
    mounted() {
        this.makeTemplate = {
            backgroundUrl: '',
            sprites: []
        };
        this.modelName = '';
        if (this.$route.params.content) {
            this.makeTemplate = this.$route.params.content;
        }
        if (this.$route.params.name) {
            this.modelName = this.$route.params.name;
        }
        if (this.$route.params.id) {
            this.formData.id = this.$route.params.id;
        }
        // 背景图片
        this.backgroundImages = [];
        util.ajax.post('/busine/background/findAll', util.toFormData({
            organizeid: this.baseuser.orgId
        })).then(res => {
            let backgroundList = res.data.data;
            backgroundList.forEach((item, index) => {
                this.backgroundImages.push(CONSTANTS.SERVER_HOST + item.url);
            });
        });

        // 章
        this.seals = [];
        util.ajax.post('/busine/chapter/findAll', util.toFormData({
            organizeid: this.baseuser.orgId
        })).then(res => {
            let chapterList = res.data.data;
            chapterList.forEach((item, index) => {
                this.seals.push({
                    organization: item.name,
                    seal_url: CONSTANTS.SERVER_HOST + item.cover
                });
            });
        })
        let fontSize = [];
        for (let i = 1; i <= 500; i++) {
            fontSize.push(i);
        }
        $('#editor').froalaEditor({
            language: 'zh_cn',
            toolbarButtons: ['color', 'fontFamily', 'fontSize', 'bold'],
            fontFamily: {
                'SimSun': '宋体',
                'SimHei': '黑体',
                'Microsoft YaHei': '微软雅黑',
                'PingFang SC': '苹方',
                'KaiTi': '楷体',
                'NSimSun': '新宋体',
                'FangSong': '仿宋'
            },
            fontSize: fontSize
        })

        $('#editor').on('froalaEditor.contentChanged', (e, editor, keyupEvent) => {
            if (this.activeSpriteIndex > -1) {
                let currSprite = this.makeTemplate.sprites[this.activeSpriteIndex];
                // currSprite.content = editor.html.get(true);
                // this.$refs.dndContainer.updateSpriteText(this.activeSpriteIndex, `$@$${editor.html.get(true)}$@$`)
                this.$refs.dndContainer.updateSpriteText(this.activeSpriteIndex, `${editor.html.get(true)}`)
                if (currSprite.name === 'name' || currSprite.name === 'diplomas' || currSprite.name === 'theme') {
                    var tdiv = document.createElement('div');
                    tdiv.innerHTML = currSprite.content;
                    currSprite.text = tdiv.innerText;
                }
            }
        })

        window.addEventListener('resize', this.onResize)
        this.onResize()

    },
    methods: {
        setAlign(align) {
            /* var clone = this.makeTemplate.sprites[this.activeSpriteIndex];
            if (clone.type === 'variable') {
                var content = '<div style="width:' + this.variableWidth + 'px;text-align:' + align + ';"><span style="font-size: 15px;">' + clone.text + '</span></div>';
                if (align === 'left') {
                    content = '<span style="font-size: 15px;white-space: nowrap;">' + clone.text + '</span>';
                }
                this.makeTemplate.sprites[this.activeSpriteIndex].content = content;
            } */
            this.makeTemplate.sprites[this.activeSpriteIndex].align = align
        },
        activateSprite(i) {
            this.activeSpriteIndex = i;

            let currSprite = this.makeTemplate.sprites[i];
            if (currSprite && (currSprite.type === 'text' || currSprite.type === 'variable')) {
                $('#editor').froalaEditor('html.set', currSprite.content);
                $('#editor').froalaEditor('edit.on')
            } else {
                $('#editor').froalaEditor('edit.off')
            }
        },
        addText() {
            this.makeTemplate.sprites.push({
                type: 'text',
                content: `<span style="font-size: ${this.fontSize}px;">请输入内容</span>`,
                x: 0,
                y: 0,
                align: 'left'
            })
            const index = this.makeTemplate.sprites.length - 1
            this.activateSprite(index)

            this.$nextTick(() => {
                const { width, height } = this.$refs.dndContainer.measureSpriteSize(index)
                Object.assign(this.makeTemplate.sprites[index], { width, height })
            })
        },
        addVariable(i) {
            if (!this.variableExist(i)) {
                let variable = this.variables[i];
                let text = variable.placeholder;
                let content = `<span style="font-size: ${this.fontSize}px;white-space: nowrap;">${text}</span>`
                this.makeTemplate.sprites.push({
                    type: 'variable',
                    name: variable.name,
                    text: text,
                    content: content,
                    x: 0,
                    y: 0,
                    align: 'left'
                });
                const index = this.makeTemplate.sprites.length - 1
                this.activateSprite(index);

                this.$nextTick(() => {
                    const { width, height } = this.$refs.dndContainer.measureSpriteSize(index)
                    Object.assign(this.makeTemplate.sprites[index], { width, height })
                })
            }
        },
        addSeal(i) {
            let sealUrl = this.seals[i].seal_url;
            this.getImageRect(sealUrl).then(({ width, height }) => {
                this.makeTemplate.sprites.push({
                    type: 'picture',
                    imageSrc: sealUrl,
                    width: DEFAULT_SEAL_WIDTH,
                    height: DEFAULT_SEAL_WIDTH / (width / height),
                    // name: this.seals[i].organization,
                    x: 0,
                    y: 0
                });
                this.activateSprite(this.makeTemplate.sprites.length - 1);
            });
        },
        fileChanged(e, type) {
            if (e.currentTarget.files && e.currentTarget.files[0]) {
                let reader = new FileReader();
                reader.addEventListener('load', (e) => {
                    if (type === 'background') {
                        this.imageDataUrl = e.target.result;
                    } else if (type === 'picture') {
                        this.getImageRect(e.target.result).then(({ width, height }) => {
                            this.makeTemplate.sprites.push({
                                type: 'picture',
                                imageSrc: e.target.result,
                                width: DEFAULT_SEAL_WIDTH,
                                height: DEFAULT_SEAL_WIDTH / (width / height),
                                x: 0,
                                y: 0
                            });
                        });
                    }
                }, { once: true });
                reader.readAsDataURL(e.currentTarget.files[0]);
            }
        },
        getImageRect(url) {
            return new Promise((resolve, reject) => {
                let img = new Image();
                img.addEventListener('load', function () {
                    resolve(img);
                });
                img.src = url;
            });
        },
        exportImage() {
            this.activeSpriteIndex = -1;
            this.$nextTick(() => {
                const done = this.$refs.dndContainer.capture()
                domtoimage.toJpeg(this.$el.querySelector('.image-edit'), {
                    quality: 1
                }).then(function (dataUrl) {
                    done()
                    var link = document.createElement('a');
                    link.download = '奖状预览.jpeg';
                    link.href = dataUrl;
                    link.click();
                });
            });
        },
        removeSprite() {
            this.makeTemplate.sprites.splice(this.activeSpriteIndex, 1);
            this.activateSprite(this.makeTemplate.sprites.length - 1);
        },
        pickBackgroundImage() {
            this.bgPickerVisible = true;
        },
        selectBg(bgUrl) {
            this.makeTemplate.backgroundUrl = bgUrl;

            // this.render.bgOriginWidth = 0;
            // this.render.bgOriginHeight = 0;

            this.bgPickerVisible = false;
        },

        variableExist(i) {
            let addedVars = this.makeTemplate.sprites.filter((item) => item.type === 'variable');
            if (addedVars.length > 0) {
                return addedVars.findIndex(item => item.name && item.name === this.variables[i].name) > -1;
            } else {
                return false;
            }
        },

        showJson() {
            console.log(JSON.stringify(this.makeTemplate));
        },
        save() {
            let makeTemplate = this.makeTemplate;
            let haveName = true;
            makeTemplate.sprites.forEach(item => {
                if (item.name === 'name') {
                    haveName = false;
                }
            })
            if (haveName) {
                this.$Modal.error({
                    title: '',
                    content: '请先在模板中设置姓名！'
                })
                return;
            }
            let formData = {};
            for (let key in this.formData) {
                formData[key] = this.formData[key];
            }
            formData['orgId'] = this.baseuser.type === 2 ? this.baseuser.orgId : (formData['orgId'] ? formData['orgId'] : '');
            formData['createtime'] = getDate.getDate(formData['createtime'], 'time');
            formData['updatetime'] = getDate.getDate(formData['updatetime'], 'time');
            formData['content'] = JSON.stringify(makeTemplate);
            formData['name'] = this.modelName;
            if (formData['name'] === '') {
                this.$Modal.error({
                    title: '',
                    content: '模板名称不能为空！'
                })
                return;
            }

            let $image = this.$refs.dndContainer.$image
            $image.setAttribute('crossOrigin', 'Anonymous')
            let _this = this;
            _this.$nextTick().then(() => {
                const done = this.$refs.dndContainer.capture()
                domtoimage.toPng($image, {
                    quality: 1
                }).then(function (dataUrl) {
                    done()
                    util.ajax.post('/upload/uploadPrize', util.toFormData({
                        dataUrl: dataUrl
                    })).then(res => {
                        formData['path'] = res.data.data.imgPath;
                        util.ajax.post('/busine/model/save', util.toFormData(formData)).then(res => {
                            if (res.data.message === 'SUCCESS') {
                                _this.editModal = false;
                                _this.$Message.success('保存成功！');
                                _this.back();
                            } else {
                                _this.$Message.warning(res.data.message || '未知错误！');
                            }
                        });
                    });
                });
            });
        },
        back() {
            this.$router.push({
                path: 'prizemodel',
                name: 'prizemodel'
            });
        },
        addQRcode() {
            let sealUrl = this.QRcode;
            this.getImageRect(sealUrl).then(({ width, height }) => {
                this.makeTemplate.sprites.push({
                    type: 'picture',
                    imageSrc: sealUrl,
                    width: DEFAULT_SEAL_WIDTH,
                    height: DEFAULT_SEAL_WIDTH / (width / height),
                    name: 'QRcode',
                    x: 0,
                    y: 0
                });
                this.activateSprite(this.makeTemplate.sprites.length - 1);
            });
        },
        toggleFullscreen() {
            if (!this.isFullscreen) {
                this.$el.querySelector('.drag-drop-box').requestFullscreen()
            } else {
                document.exitFullscreen()
            }
            this.isFullscreen = !this.isFullscreen
        },
        onResize() {
            console.log('on resize')
            let containerWidth = 0, containerHeight = 0
            if (this.isFullscreen) {
                const rect = document.body.getBoundingClientRect()
                containerWidth = rect.width
                containerHeight = rect.height
            } else {
                const rect = this.$el.getBoundingClientRect()
                containerWidth = rect.width - 600
                containerHeight = rect.height
            }
            this.$refs.dndContainer.applyContainerSize(containerWidth, containerHeight)
        },
        replaceText(name, text) {
            let currSprite = this.makeTemplate.sprites;
            var objE = document.createElement('div');
            currSprite.forEach((item, index) => {
                if (item.name === name) {
                    objE.innerHTML = item.content;
                    objE.getElementsByTagName('span')[0].innerHTML = text;
                    this.$refs.dndContainer.updateSpriteTextByName(item.name, objE.innerHTML);
                }
            });
        },
        goPreview() {
            this.loadTheme();
            this.preTemplate = JSON.stringify(this.makeTemplate);
            this.isPreview = true;
        },
        backPreview() {
            this.isPreview = false;
            this.makeTemplate = JSON.parse(this.preTemplate);
        },
        loadTheme() {
            util.ajax.post('/busine/theme/findAll', util.toFormData({
                organizeid: (this.baseuser.type === 2 ? this.baseuser.orgId : '')
            })).then(res => {
                let themeList = [];
                let allTheme = res.data.data;
                allTheme.forEach((item, index) => {
                    if (item.level === 1) {
                        let childernList = [];
                        allTheme.forEach((citem, index) => {
                            if (citem.level === 2 && citem.parentId === item.id) {
                                childernList.push({
                                    value: citem.id,
                                    label: citem.name
                                });
                            }
                        });
                        themeList.push({
                            value: item.id,
                            label: item.name,
                            children: childernList
                        });
                    }
                });
                this.themeList = themeList;
            });
        },
        setTheme(labels) {
            const index = labels.length - 1;
            return labels[index];
        },
        themeChange(value, selectData) {
            const index = value.length - 1;
            this.themeId = value[index];
            this.replaceText('theme', selectData[index].label);
            this.loadDiploma();
        },
        loadDiploma() {
            util.ajax.post('/busine/diplomas/findByTheme', util.toFormData({
                themeId: this.themeId
            })).then(res => {
                this.diplomasList = res.data.data;
            });
        },
        dipChange(data) {
            this.replaceText('diplomas', data.label);
            this.loadMember(data.value);
        },
        loadMember(diplomasId) {
            this.allMember = [];
            if (this.themeId !== '') {
                util.ajax.post('/busine/theme/member/getMember', util.toFormData({
                    themeId: this.themeId,
                    diplomasId: diplomasId
                })).then(res => {
                    let data = res.data.data;
                    data.forEach((item) => {
                        this.allMember.push({
                            key: item.id,
                            label: item.member.realname + '-' + item.member.phone,
                            name: item.team ? item.team : item.member.realname,
                            memberId: item.memberId,
                            spare1: item.spare1,
                            spare2: item.spare2,
                            spare3: item.spare3,
                            diplomasId: item.diplomasId,
                            diplomas: item.diplomas.name,
                            school: item.member.school
                        });
                    });
                });
            }
        },
        memberChange() {
            this.allMember.forEach(item => {
                if (this.preForm.memberId === item.key) {
                    let sprites = this.makeTemplate.sprites;
                    var objE = document.createElement('div');
                    sprites.forEach((citem) => {
                        objE.innerHTML = citem.content;
                        if (citem.name && citem.name === 'name') {
                            var perNum = this.preForm.perNum;
                            var nameList = item.name.split('、');
                            var name = '';
                            for (var i = 0; i < nameList.length; i++) {
                                if (i > 0) {
                                    if (i % perNum === 0) {
                                        name += '<br>';
                                    } else {
                                        name += '、';
                                    }
                                }
                                name += nameList[i];
                            }
                            objE.getElementsByTagName('span')[0].innerHTML = name;
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);
                        } else if (citem.name && citem.name !== 'theme') {
                            objE.getElementsByTagName('span')[0].innerHTML = item[citem.name];
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);
                        }
                    });
                }
            });
        },
        numChange() {
            this.allMember.forEach(item => {
                if (this.preForm.memberId === item.key) {
                    let sprites = this.makeTemplate.sprites;
                    var objE = document.createElement('div');
                    sprites.forEach((citem) => {
                        if (citem.name && citem.name === 'name') {
                            objE.innerHTML = citem.content;
                            var perNum = this.preForm.perNum;
                            var nameList = item.name.split('、');
                            var name = '';
                            for (var i = 0; i < nameList.length; i++) {
                                if (i > 0) {
                                    if (i % perNum === 0) {
                                        name += '<br>';
                                    } else {
                                        name += '、';
                                    }
                                }
                                name += nameList[i];
                            }
                            objE.getElementsByTagName('span')[0].innerHTML = name;
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);
                        }
                    });
                }
            });
        }
    },
    computed: {
        currSprite() {
            /* if (this.activeSpriteIndex > -1) {
                const currSprite = this.makeTemplate.sprites[this.activeSpriteIndex]
                return currSprite.align
            } else {
                return ''
            } */
            return this.makeTemplate.sprites[this.activeSpriteIndex]
        },
        currAlign() {
            return this.currSprite ? this.currSprite.align : ''
        },
        fontSize() {
            return this.defaultFontSize / this.$refs.dndContainer.render.bgScale
        }
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.onResize);
    }
};